package com.market.fleamarket.config;

import com.market.fleamarket.interceptor.AuthInterceptor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.config.annotation.*;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Value("${file.upload-dir:uploads}")
    private String uploadDir;

    @Bean
    public AuthInterceptor authInterceptor() {
        return new AuthInterceptor();
    }

    @PostConstruct
    public void init() {
        try {
            // 确保上传目录存在
            Path uploadPath = Paths.get(uploadDir);
            String absolutePath = uploadPath.toAbsolutePath().toString();
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
                System.out.println("WebConfig: 创建上传目录: " + absolutePath);
            } else {
                System.out.println("WebConfig: 上传目录已存在: " + absolutePath);
            }

            // 检查目录是否可写
            if (!Files.isWritable(uploadPath)) {
                System.err.println("警告: 上传目录不可写: " + absolutePath);
            } else {
                System.out.println("WebConfig: 上传目录可写: " + absolutePath);
            }

            // 创建一个测试文件
            try {
                Path testFile = uploadPath.resolve("test.txt");
                Files.write(testFile, ("测试文件 - " + System.currentTimeMillis()).getBytes());
                System.out.println("WebConfig: 测试文件创建成功: " + testFile.toAbsolutePath());
            } catch (Exception e) {
                System.err.println("WebConfig: 创建测试文件失败: " + e.getMessage());
            }

        } catch (IOException e) {
            System.err.println("WebConfig: 初始化上传目录失败: " + e.getMessage());
        }
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(authInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns("/error");
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 配置外部资源访问
        Path uploadPath = Paths.get(uploadDir);
        String uploadAbsolutePath = uploadPath.toFile().getAbsolutePath();

        // 确保路径以分隔符结束
        if (!uploadAbsolutePath.endsWith(File.separator)) {
            uploadAbsolutePath = uploadAbsolutePath + File.separator;
        }

        // 打印静态资源映射信息便于调试
        System.out.println("配置静态资源映射: /uploads/** -> file:" + uploadAbsolutePath);

        // 确保映射路径格式正确
        String locationPath = "file:" + uploadAbsolutePath;
        System.out.println("最终资源路径: " + locationPath);

        registry.addResourceHandler("/uploads/**")
                .addResourceLocations(locationPath);

        // 添加默认静态资源映射
        registry.addResourceHandler("/static/**")
                .addResourceLocations("classpath:/static/");
    }

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        // 只保留没有对应Controller方法的路径映射
        registry.addViewController("/logout").setViewName("redirect:/login");
    }

    /**
     * 诊断控制器，用于检查上传目录配置
     */
    @RestController
    public static class DiagnosticController {
        @Value("${file.upload-dir:uploads}")
        private String uploadDir;

        @GetMapping("/api/diagnostic/upload-dir")
        public Map<String, Object> checkUploadDir() {
            Map<String, Object> result = new HashMap<>();
            try {
                Path path = Paths.get(uploadDir);
                String absolutePath = path.toAbsolutePath().toString();

                result.put("configuredPath", uploadDir);
                result.put("absolutePath", absolutePath);
                result.put("exists", Files.exists(path));
                result.put("isDirectory", Files.isDirectory(path));
                result.put("isWritable", Files.isWritable(path));
                result.put("isReadable", Files.isReadable(path));

                if (Files.exists(path)) {
                    File[] files = path.toFile().listFiles();
                    if (files != null) {
                        result.put("fileCount", files.length);
                        String[] fileNames = new String[files.length];
                        for (int i = 0; i < files.length; i++) {
                            fileNames[i] = files[i].getName();
                        }
                        result.put("files", fileNames);
                    } else {
                        result.put("fileCount", 0);
                        result.put("files", new String[0]);
                    }
                }
            } catch (Exception e) {
                result.put("error", e.getMessage());
                result.put("stackTrace", e.getStackTrace());
            }
            return result;
        }
    }
} 